package com.patrick.api.starter.config;

import com.patrick.patrick.core.swagger.OpenSwaggerManager;
import io.swagger.annotations.Api;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.Contact;
import springfox.documentation.service.SecurityScheme;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.SecurityConfiguration;
import springfox.documentation.swagger.web.SecurityConfigurationBuilder;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.Collections;

/**
 * @author patrick
 * @date 2020/5/28 2:32 下午
 * @Des swagger配置类
 * 最簡單的事是堅持，最難的事還是堅持
 */
@Configuration
@EnableConfigurationProperties({OpenSwaggerManager.class})
@ConditionalOnProperty(prefix = "opencloud.swagger2", name = "enabled", havingValue = "true")
@EnableSwagger2
public class SwaggerAutoConfiguration {
  private OpenSwaggerManager openSwaggerManager;
  @Bean
  public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
      .apiInfo(apiInfo())
      .select()
      .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
      .paths(PathSelectors.any())
      .build()
      .securitySchemes(Collections.singletonList(securityScheme()));
  }

  @Bean
  public SecurityConfiguration security() {
    return SecurityConfigurationBuilder.builder()
      .clientId(openSwaggerManager.getClientId())
      .clientSecret(openSwaggerManager.getClientId())
      .realm(openSwaggerManager.getClientId())
      .appName("")
      .scopeSeparator(",").build();
  }
  /**
   * oauth2认证添加头信息
   * @return
   */
  @Bean
  SecurityScheme securityScheme() {
    return new ApiKey("BearerToken", "Authorization", "header");
  }
  //配置头信息
  private ApiInfo apiInfo() {
    return new ApiInfo(
      openSwaggerManager.getTitle(),
      "银行理财：https://www.qianxs.com，欢迎大家访问。",
      "API V1.0",
      "Terms of service",
      new Contact("名字想好没", "https://www.qianxs.com", "gaopeng@qianxs.com"),
      "QIQX", "http://www.qianxs.com", Collections.emptyList());
  }
}
